<?php

define("DB_DEFAULT_LIMIT", 10);

/**
 * Connect to the database server and use the database for a particular database link
 * @param string $dblinkname Default 'readwrite'; you can change this to set up additional global database links, eg "read" and "write"
 * @throws Exception
 */
function establish_db_link($dblinkname = 'readwrite') {
    global $CONFIG, $dblink;

    if (!isset($dblink)) {
        $dblink = array();
    }

    $dbhost = $CONFIG->dbhost;
    $dbuser = $CONFIG->dbuser;
    $dbpass = $CONFIG->dbpass;
    $dbname = $CONFIG->dbname;

    // connect to database
    if (!$dblink[$dblinkname] = mysql_connect($dbhost, $dbuser, $dbpass, true)) {
        throw new Exception("[Database] Database Exception: WrongCredentials");
    }

    if (!mysql_select_db($dbname, $dblink[$dblinkname])) {
        throw new Exception("[Database] Database Exception: NoConnect");
    }
}

/**
 * Establish all database connections
 */
function setup_db_connections() {
    establish_db_link('read');
    establish_db_link('write');
}

/**
 * Get db link resource
 * @param string $dblinktype
 * @return mixed
 */
function get_db_link($dblinktype) {
    global $dblink;

    if (isset($dblink[$dblinktype])) {
        return $dblink[$dblinktype];
    } else {
        return $dblink['readwrite'];
    }
}

/**
 * Execute a query
 *
 * @param string $query the query
 * @param resource $dblink the DB link
 * @return resource Returns a the result of mysql_query
 * @throws DataBaseException
 */
function execute_query($query, $dblink) {
    global $CONFIG;
    if ((isset($CONFIG->debug)) && ($CONFIG->debug == true)) {
        error_log("DB query \"$query\" executing..");
    }
    $result = mysql_query($query, $dblink);

    if (mysql_errno($dblink)) {
        throw new DataBaseException("[Database] ".mysql_error($dblink)." QUERY: ".$query);
    }

    return $result;
}

/**
 * @param string $query
 * @param string $callback
 * @return array|bool
 */
function get_data($query, $callback = "") {
    global $CONFIG;

    $dblink = get_db_link('read');

    $result_array = array();

    if ($result = execute_query("$query", $dblink)) {
        while ($row = mysql_fetch_object($result)) {
            if (!empty($callback) && is_callable($callback)) {
                $row = $callback($row);
            }
            if ($row) $result_array[] = $row;
        }
    }

    if (empty($result_array)) {
        if ((isset($CONFIG->debug)) && ($CONFIG->debug == true)) {
            error_log("[Database] WARNING: DB query \"$query\" returned no results.");
        }
        return false;
    }

    return $result_array;
}

/**
 * Use this function to get a single data row from the database
 * @param string $query the query to run
 * @return object A single database result object
 */
function get_data_row($query) {
    global $CONFIG;

    $dblink = get_db_link('read');

    if ($result = execute_query("$query", $dblink)) {
        $row = mysql_fetch_object($result);

        if ($row) return $row;
    }

    if ((isset($CONFIG->debug)) && ($CONFIG->debug==true))
        error_log("[Database] WARNING: DB query \"$query\" returned no results.");

    return false;
}

/**
 *  Use this function to insert database data; return id or false
 * @param string $query the query to run
 * @return bool|int the database if of the inserted row
 */
function insert_data($query) {
    global $CONFIG;

    $dblink = get_db_link('write');
    if (execute_query("$query", $dblink)) {
        return mysql_insert_id($dblink);
    }
    return false;
}

/**
 * Update database data
 * @param string $query the query to run
 *
 * @return bool true on success, or false on failure
 */
function update_data($query) {
	global $CONFIG;

	$dblink = get_db_link('write');

	if (execute_query("$query", $dblink)) {
		return true;
	}

	return false;
}